using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ByteDance.Live.Foundation.Logging;
using ByteDance.LiveOpenSdk.Runtime.Utilities;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using Microsoft.CSharp;

namespace Douyin.LiveOpenSDK.Samples
{
    /// <summary>
    /// <para>
    /// 负责控制示例场景 SampleGameScene 的行为。
    /// </para>
    /// <para>
    /// 使用方法：点击“指令直推模式”或“抖音云模式”二者之一，然后观察日志窗口。
    /// 两种模式互斥，无法同时生效。
    /// </para>
    /// <para>
    /// 需要配置参数的类：
    /// <list type="bullet">
    /// <item><see cref="SampleLiveOpenSdkManager"/></item>
    /// <item><see cref="SampleDyCloudManager"/></item>
    /// </list>
    /// </para>
    /// </summary>
    public class SampleGameStartup : MonoBehaviour
    {
        public Text LogText;

        private readonly LogConsole _logConsole = new LogConsole();
        private LogWriter Log { get; } = new LogWriter(SdkUnityLogger.LogSink, "SampleGameStartup");

        private void Awake()
        {
            // 把 SDK 的日志输出放到场景上
            _logConsole.Text = LogText;
            SdkUnityLogger.OnRichLog += _logConsole.WriteLog;
        }

        private async void Start()
        {
            // 可设置日志等级，调试时可使用较详细的日志
            SdkUnityLogger.MinSeverity = Severity.Verbose;
            // 任何玩法需设置
            string appId = "tt2692502fb99986b010";
            // 初始化直播开放 SDK
            Log.Info($"开始LiveOpenSdk初始化 AppId: {appId}");
            SampleLiveOpenSdkManager.Initialize(appId);

           

           if (string.IsNullOrEmpty(SampleLiveOpenSdkManager.Token))
            {
                Log.Warning("警告：SDK 未能从命令行获得 token，请从直播伴侣启动 exe 或手动提供 token");
                Log.Info("手动复制token：15225006562");
                SampleLiveOpenSdkManager.Token = "15225006562";
            }
            //初始化后台获取后台给的token和romid
           
        }


       
        private async void StartRound()
        {
            var result = await SampleRoundManager.Instance.StartRoundAsync();
        }

        private async void EndRound()
        {
            var result = await SampleRoundManager.Instance.EndRoundAsync();
        }

    internal class LogConsole
    {
        private const int MaxCount = 15;
        private readonly Queue<string> _messageQueue = new Queue<string>();

        public Text Text { get; set; }

        public Severity MinSeverity = Severity.Info;

        public void WriteLog(Severity severity, string richText)
        {
            if (!severity.IsAtLeast(MinSeverity)) return;

            while (_messageQueue.Count >= MaxCount)
            {
                _messageQueue.Dequeue();
            }

            _messageQueue.Enqueue(richText);

            if (Text == null) return;

            Text.text = string.Join("\n", _messageQueue);
        }
    }
    }
}